#!/bin/bash

helpstring='-------------------
  n: skip track
  p: pause
  q: quit
  t: statistics
-------------------'
if [ -z `which ffplay` ]; then
	echo "ffmpeg is missing"
	exit 2
fi

if [ $# -ne 1 ]; then
	echo "path to folder required"
	exit 2
fi

if [ ! -d "$1" ]; then
	echo "path not found: $1"
	exit 2
fi

player_out=$(mktemp -u)
paused=0
stats=0

mkfifo $player_out

exec 3<>$player_out

rm -f $player_out

echo -e "shell MP3 player\n""$helpstring"

trap "pkill -P $$; exit" EXIT TERM INT

trap "paused=0; stats=0; spawn_stats; print_song_name" USR2

(
IFS='
'
set -f
for line in $(find "$1" -type f \( -iname "*.mp3" -o -iname "*.m4a" \) | sort -V); do
	ffplay -hide_banner -stats -loglevel info -nodisp -autoexit -i "$line" >&3 2>&1 &
	ffpid=$!
	kill -s USR2 $$
	wait $ffpid
done
set +f
unset IFS
kill -s TERM $$
)&

playlist_pid=$!

print_song_name() {
	song_pid=$(ps --ppid $playlist_pid | sed -n 's|^\s*\([0-9]\+\)\s.*\sffplay.*|\1|p')
	test $song_pid || exit
	song_name=$(ps -fp $song_pid | sed -n 's|.*\sffplay\s.*\s-i\s\(.*\)|\1|p')
	misc_info=$(ffprobe -hide_banner -v quiet -pretty -of csv=s=\| -select_streams a -show_entries stream=duration,bit_rate,channels,sample_rate "$song_name" | sed -e 's/^stream//' -e 's/|/  /g' | awk -F '  ' '{printf "  %s  %s  %s  %s", $4, $2, $5, (($3 == 2) ? "stereo" : (($3 == 1) ? "mono" : "")); }')
	test $paused -eq 0 && printf "%s\n%s\n" "$song_name" "$misc_info" || printf "%s\n%s\n" "$song_name <paused>" "$misc_info"
}

spawn_stats() {
	stats_pid=$(ps --ppid $$ | sed -n 's|^\s*\([0-9]\+\)\s.*\scat.*|\1|p')
	[ ! -z $stats_pid ] && [ -d "/proc/${stats_pid}" ] && kill $stats_pid
	if [ $stats -eq 0 ]; then
		cat <&3 >/dev/null & 
	else
		cat <&3 &
	fi
}

while read -sn1 keyin; do
	if [ "$keyin" = 'q' ]; then
		kill $playlist_pid
		kill $song_pid
		break;
	elif [ "$keyin" = 'n' ]; then
		[ "$(ps -o state= -p $song_pid)" = T ] && kill -CONT $song_pid 
		kill $song_pid
	elif [ "$keyin" = 'p' ]; then
		if [ -d "/proc/${song_pid}" ]; then
			if [ $paused -eq 0 ]; then
				paused=1
				kill -TSTP $song_pid
			else
				paused=0
				kill -CONT $song_pid
			fi
			print_song_name
		fi
	elif [ "$keyin" = 't' ]; then
		if [ $stats -eq 0 ]; then
			stats=1
		else
			stats=0
		fi
		spawn_stats
		test $stats -eq 0 && print_song_name
	else
		echo "$helpstring"
		print_song_name
	fi
done

exec 3<&-

# ffplay -f lavfi -i "sine=frequency=1000:duration=5" -autoexit -nodisp
